﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Domain.UserManageDomain;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoWcsManage;
using Zocono.WMS.Infrastructure.BaseRepository;

namespace Zocono.WCS.Application.AppUserManage
{
    public class UserInfoApp
    {
        private readonly IRoleInfoService _RoleInfoService;
        private readonly IUserInfoService _Userservice;
        private readonly IRoleRightInfoService _RoleRightInfoService;
        private readonly IUserRoleInfoService _UserRoleInfoService;
        private readonly IMenuInfoService _MenuInfoService;
        private readonly IMapper _Mapper;

        private readonly ISnowflake _snowflake;

        public UserInfoApp(IUserInfoService userService, IMapper mapper, IRoleRightInfoService userRightInfo,
            IMenuInfoService menuInfoService, ISnowflake snowflake, IUserRoleInfoService userRoleInfoService,
            IRoleInfoService roleInfoService)
        {
            _Userservice = userService;
            _RoleRightInfoService = userRightInfo;
            _MenuInfoService = menuInfoService;
            _Mapper = mapper;
            _snowflake = snowflake;
            _UserRoleInfoService = userRoleInfoService;
            _RoleInfoService = roleInfoService;
        }

        public async Task<List<UserInfoApiDto>> GetUserListAsync()
        {
            return await _Userservice.GetUserListAsync();
        }

        public async Task<UserInfoApiDto> LoginAsync(string userName, string password)
        {
            var userinfoDto = await _Userservice.LoginAsync(userName, password);
            return userinfoDto;
        }

        public async Task<bool> UpdatePasswordAsync(long ID, string newPassword)
        {
            return await _Userservice.UpdatePasswordAsync(ID, newPassword);
        }

        public async Task<bool> InitPasswordAsync(List<string> userNames)
        {
            return await _Userservice.InitPasswordAsync(userNames);
        }


        public async Task<List<UserRoleInfoDto>> GetUserRoleInfos(long userID)
        {
            return await _UserRoleInfoService.GetUserRoleInfos(userID);
        }


        public async Task<UserInfoApiDto> GetUserByIDAsync(long userID)
        {
            return await _Userservice.GetUserByIDAsync(userID);
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="menuInfoDto"></param>
        /// <returns></returns>
        public async Task<bool> AddMenuAsync(MenuInfoDto menuInfoDto)
        {
            return await _MenuInfoService.AddMenuAsync(menuInfoDto);
        }


        public async Task<bool> UpdateMenuInfoAsync(MenuInfoDto menuInfoDto)
        {
            return await _MenuInfoService.UpdateMenuInfoAsync(menuInfoDto);
        }

        /// <summary>
        /// 添加用户和权限
        /// </summary>
        /// <param name="userMangerDto"></param>
        /// <returns></returns>
        public async Task<bool> InsertUserRoleAsync(List<UserMangerDto> userMangerDto)
        {
            List<UserRoleInfoDto> userRoleInfoDto = new List<UserRoleInfoDto>();
            UserInfoApiDto userInfoDto = new UserInfoApiDto();
            try
            {
                _UserRoleInfoService.Begin();

                #region 单条插入
                var userdto = userMangerDto.Where(x => x.UserName != null).FirstOrDefault();
                _Mapper.Map(userdto, userInfoDto);
                userInfoDto.Password = GenerateMD5.DESEncrypt(userdto.Password);
                userInfoDto.UserID = _snowflake.GetId();
                userInfoDto.IsDelete = false;
                userInfoDto.UpdateTime = DateTime.Now;
                await _Userservice.AddUserAsync(userInfoDto);



                var userRoledto = userMangerDto.Where(x => x.CreateUserName.IsEmpty() == false).FirstOrDefault();

                //userRoleInfoDto.CreateUserName = string.Empty;
                userMangerDto.Where(x => x.RoleID.IsEmpty() == false&& x.RoleID!=0).ForEach(x =>
                   {
                       userRoleInfoDto.Add(new UserRoleInfoDto
                       {
                           CreateUserName = userRoledto.CreateUserName,
                           UserID = userInfoDto.UserID,
                           UpdateTime = DateTime.Now,
                           IsDelete = false,
                           UserRoleID = _snowflake.GetId(),
                           RoleID = x.RoleID
                       });


                   });
                await _UserRoleInfoService.InsertUserRoleInfo(userRoleInfoDto);

                _UserRoleInfoService.Commit();

                #endregion

                return true;

            }
            catch (Exception ex)
            {
                _UserRoleInfoService.RollBack();
                throw new Exception(ex.Message);
            }

        }


        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public async Task<bool> DeleteUserAsync(long userID)
        {
            try
            {
                _UserRoleInfoService.Begin();
                var resUserRole = await _UserRoleInfoService.DeleteUserRoleInfo(x => x.UserID == userID);
                var resUser = await _Userservice.DeleteUserAsync(userID);
                _UserRoleInfoService.Commit();
                return resUserRole == resUser;

            }
            catch (Exception ex)
            {
                _UserRoleInfoService.RollBack();
                throw new Exception(ex.Message);
            }

        }


        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> DeleteRoleAsync(long roleID)
        {
            try
            {
                _UserRoleInfoService.Begin();
                //删除用户和角色
                var resUserRole = await _UserRoleInfoService.DeleteUserRoleInfo(x => x.RoleID == roleID);
                //删除角色和权限
                var resRoleRight = await _RoleRightInfoService.DeleteRoleRightAsync(x => x.RoleID == roleID);
                //删除角色
                var resRole = await _RoleInfoService.DeleteRoleInfoAsync(roleID);
                _UserRoleInfoService.Commit();
                return resUserRole == resRoleRight == resRole;
            }
            catch (Exception ex)
            {
                _UserRoleInfoService.RollBack();
                throw new Exception(ex.Message);
            }

        }


        /// <summary>
        /// 修改用户角色
        /// </summary>
        /// <param name="userRoleInfoDtos"></param>
        /// <returns></returns>
        public async Task<bool> UpdateUserRoleAsync(List<UserMangerDto> UserMangerDtos)
        {
            List<UserRoleInfoDto> userRoleInfoDtolist = new List<UserRoleInfoDto>();

            UserInfoApiDto userInfoDto = new UserInfoApiDto();

            _UserRoleInfoService.Begin();
            try
            {
                #region 单条插入
                var userdto = UserMangerDtos.Where(x => x.UserID.IsEmpty()==false&& x.UserID!=0&&x.UserName!=null).FirstOrDefault();
                _Mapper.Map(userdto, userInfoDto);
                userInfoDto.Password = GenerateMD5.DESEncrypt(userdto.Password);
                await _Userservice.UpdateUserInfoAsync(userdto.UserID, userInfoDto.Password, userdto.UserName,
                userdto.JobNumber,DateTime.Now);

                var result = UserMangerDtos.Where(x => x.UserID.IsEmpty() == false).FirstOrDefault();
                await _UserRoleInfoService.DeleteUserRoleInfo(x => x.RoleID == result.RoleID);



                UserMangerDtos.Where(x => x.RoleID.IsEmpty() == false&& x.RoleID!=0).ForEach( x =>
                 {
                     userRoleInfoDtolist.Add(new UserRoleInfoDto
                     {
                         UserID = result.UserID,
                         CreateUserName = result.CreateUserName,
                         UpdateTime = DateTime.Now,
                         IsDelete = false,
                         UserRoleID = _snowflake.GetId(),
                         RoleID = x.RoleID
                     });
                 });
                await _UserRoleInfoService.InsertUserRoleInfo(userRoleInfoDtolist);
                _UserRoleInfoService.Commit();
                return true;
            }
            catch (Exception ex)
            {
                _UserRoleInfoService.RollBack();
                throw new Exception(ex.Message);
            }


        }


        /// <summary>
        /// 修改角色权限
        /// </summary>
        /// <param name="roleRightInfoDtos"></param>
        /// <returns></returns>
        public async Task<bool> UpdateRoleRightAsync(List<UserMangerDto> userMangerDto)
        {
            List<RoleRightInfoDto> roleRightInfoDtolist = new List<RoleRightInfoDto>();

            try
            {
                _UserRoleInfoService.Begin();
                var result = userMangerDto.Where(x => x.RoleID.IsEmpty() == false).FirstOrDefault();
                var resRoleRight = await _RoleRightInfoService.DeleteRoleRightAsync(x => x.RoleID == result.RoleID);
                //bool resRole = false;


                userMangerDto.Where(x => x.MenuID.IsEmpty() == false && x.MenuID != 0).ForEach(x =>
                {
                    roleRightInfoDtolist.Add(new RoleRightInfoDto
                    {
                        UpdateTime = DateTime.Now,
                        IsDelete = false,
                        RoleID = result.RoleID,
                        CreateUserName = result.CreateUserName,
                        RoleRightID = _snowflake.GetId(),
                        MenuID = x.MenuID
                    });
                });
                await _RoleRightInfoService.AddRoleRightAsync(roleRightInfoDtolist);

                _UserRoleInfoService.Commit();
                return true;

            }
            catch (Exception ex)
            {
                _UserRoleInfoService.RollBack();
                throw new Exception(ex.Message);
            }
        }


        /// <summary>
        /// 插入角色和权限
        /// </summary>
        /// <param name="userMangerDto"></param>
        /// <returns></returns>
        public async Task<bool> InsertRoleRightAsync(List<UserMangerDto> userMangerDto)
        {
            RoleInfoApiDto roleInfoDto = new RoleInfoApiDto();
            List<RoleRightInfoDto> roleRightInfoDtos = new List<RoleRightInfoDto>();
            RoleRightInfoDto roleRightInfoDto = new RoleRightInfoDto();
            try
            {

                _UserRoleInfoService.Begin();
                roleInfoDto.RoleID = _snowflake.GetId();
                roleInfoDto.UpdateTime = DateTime.Now;
                roleInfoDto.IsDelete = false;
                var userRoleDto = userMangerDto.Where(x => x.RoleName != null).FirstOrDefault();
                roleInfoDto.SonID = userRoleDto.RoleParentID;
                roleInfoDto.RoleName = userRoleDto.RoleName;
                roleInfoDto.CreateUserName = userRoleDto.CreateUserName;
                await _RoleInfoService.AddRoleInfoAsync(roleInfoDto);


                userMangerDto.Where(x => x.MenuID.IsEmpty() == false&& x.MenuID!=0).ForEach(x =>
                {

                    roleRightInfoDtos.Add(new RoleRightInfoDto
                    {
                        UpdateTime = DateTime.Now,
                        IsDelete = false,
                        RoleID = roleInfoDto.RoleID,
                        CreateUserName = userRoleDto.CreateUserName,
                        RoleRightID = _snowflake.GetId(),
                        MenuID = x.MenuID,
                    });
                });
                await _RoleRightInfoService.AddRoleRightAsync(roleRightInfoDtos);

                _UserRoleInfoService.Commit();

                return true;
            }
            catch (Exception ex)
            {
                _UserRoleInfoService.RollBack();
                throw new Exception(ex.Message);
            }
        }


        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <returns></returns>
        public async Task<bool> DeleteMenuAsync(long menuID)
        {
            try
            {
                _UserRoleInfoService.Begin();
                await _RoleRightInfoService.DeleteRoleRightAsync(x => x.MenuID == menuID);
                await _MenuInfoService.DeleteMenuAsync(x => x.MenuID == menuID);
                _UserRoleInfoService.Commit();
                return true;
            }
            catch (Exception ex)
            {
                _UserRoleInfoService.RollBack();
                throw new Exception(ex.Message);
            }
        }


        /// <summary>
        /// 获取用户菜单权限（登录及修改用）
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public async Task<List<RoleRightInfoDto>> GetRoleRightAsync(long userID)
        {

            return await _RoleRightInfoService.GetRoleRightAsync(userID);
        }


        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        public async Task<List<MenuInfoDto>> GetMenuAsync()
        {
            return await _MenuInfoService.GetMenuAsync();
        }


        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        public async Task<MenuInfoDto> GetMenuByIDAsync(long menuID)
        {
            return await _MenuInfoService.GetMenuByIDAsync(menuID);
        }

        /// <summary>
        /// 获取角色菜单
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleInfoApiDto>> GetRoleAsync()
        {
            return await _RoleInfoService.GetRoleInfoAsync();
        }




        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleRightInfoDto>> GetRoleMenuByIDAsync(long roleID)
        {
            return await _RoleRightInfoService.GetRoleMenuByIDAsync(roleID);
        }

    }
}
#endregion